<?php
class Admin_OrderController extends Zend_Controller_Action{

	protected $_orderform;

	public function init(){
		parent::init();
	}

	protected function getScheduleSubInfo($sid) {
		if (isset($sid)) {
			$scheduleMapper = new Admin_Model_ScheduleMapper();
			$schedule = new Admin_Model_Schedule();
			$has = $scheduleMapper->find($sid, $schedule);
			if ($has) {
				return 'From '.$schedule->_fromdate.' to '.$schedule->_todate;
			}
		}
		return '';
	}

	protected function buildUserForm($users, $userInfo) {
		$userForm = new Admin_Form_OrderUser();
		$userForm->setMethod('get');
		$userForm->bindData($users);
		$userForm->populateData($userInfo);
		$url = new Zend_View_Helper_Url();
		$action = $url->url(array('module'=>'admin',
					'controller'=> 'order','action'=>'index'),
		NULL, TRUE);
		$userForm->setAction($action);
		$this->view->userform = $userForm;
		return $userForm;
	}

	protected function buildRemainForm($userInfo) {
		$userRemainForm = new Admin_Form_UserRemain();
		$userRemainForm->setMethod('get');
		$userRemainForm->populateData($userInfo);
		$url = new Zend_View_Helper_Url();
		$action = $url->url(array('module'=>'admin',
					'controller'=> 'order','action'=>'updateremain'),
		NULL, TRUE);
		$userRemainForm->setAction($action);
		$this->view->remainform = $userRemainForm;
		return $userRemainForm;
	}

	protected function buildOrderForm($type, $user) {
		$orderForm = new Admin_Form_Order($type);

		$scheduleMapper = new Admin_Model_ScheduleMapper();
		$typeMapper = new User_Model_TypeMapper();
		$types = $typeMapper->fetchAll();
		$schedules = $scheduleMapper->fetchAll();
		$orderForm->bindData($schedules, $types, $user);

		$url = new Zend_View_Helper_Url();
		$action = $url->url(array('module'=>'admin',
					'controller'=> 'order','action'=>'addorder'),
		NULL, TRUE);
		if ($type == 'update') {
			$oid = $this->getRequest()->getParam('menu');
			if (isset($oid)) {
				$orderMapper = new User_Model_OrderMapper();
				$orderInfo = new User_Model_Order();
				if ($orderMapper->find($oid, $orderInfo) && $type == 'update') {
					$orderForm->populateData($orderInfo);
				}
			}
			$action = $url->url(array('module'=>'admin',
					'controller'=> 'order','action'=>'updateorder','user' => $user->_uid, 'menu' => $oid),
			NULL, TRUE);
		}
		$orderForm->setAction($action);
		$this->view->form = $orderForm;
		$this->_orderform = $orderForm;
		return $orderForm;
	}

	protected function buildTableOrders($uid) {
		$tableHtml = "<table cellpadding = '0' cellspacing = '0' class='table-data' border='0'>
					      <thead>
						  <tr>
						    <th>Schedule</th>
						    <th>Date</th>
						    <th>Type</th>
						    <th>Quantity</th>
						    <th>Status</th>
						    <th>Update</th>
						    <th>Delete</th>
						  </tr>
						  </thead>
					  ";
		$orderMapper = new User_Model_OrderMapper();
		$entries = $orderMapper->getOrdersNotDone($uid);

		if (isset($entries)) {
			$url = new Zend_View_Helper_Url();

			foreach ($entries as $row) {
				$rowStr = '<tr>';
				// schedule
				$sid = $row->_sid;
				$sid = $this->getScheduleSubInfo($sid);
				$rowStr = $rowStr .'<td>'.$sid.'</td>';
				// date
				$date = $row->_date;
				if (!isset($date)) {
					$date = '';
				}
				$rowStr = $rowStr .'<td>'.$date.'</td>';
				// type
				$type = $row->_type;
				if (!isset($type)) {
					$type = '';
				}
				$typeInfo = $orderMapper->getType($row->_oid);
				if (isset($typeInfo)) {
					$type = $typeInfo->_typename;
				}
				$rowStr = $rowStr .'<td>'.$type.'</td>';
				// quantity
				$quantity = $row->_quantity;
				if (!isset($quantity)) {
					$quantity = '';
				}
				$rowStr = $rowStr .'<td>'.$quantity.'</td>';
				// status
				$status = $row->_status;
				if (!isset($status)) {
					$status = '';
				}
				$rowStr = $rowStr .'<td>'.$status.'</td>';

				// update link
				$updatelink = $url->url(array('module'=>'admin', 'controller'=>'order',
					'action'=>'updateorder','user'=>$row->_uid,
					'menu'=>$row->_oid));
				if (!isset($updatelink)) {
					$updatelink = '';
				}
				$rowStr = $rowStr ."<td><a href = '".$updatelink."'>Update</a>".'</td>';
				// delete link
				$deletelink = $url->url(array('module'=>'admin', 'controller'=>'order',
					'action'=>'deleteorder','user'=>$row->_uid,
					'menu'=>$row->_oid));
				if (!isset($deletelink)) {
					$deletelink = '';
				}
				$rowStr = $rowStr ."<td><a href = '".$deletelink."'>Delete</a>".'</td>';
				$rowStr = $rowStr.'</tr>';
				$tableHtml = $tableHtml.$rowStr;
			}
		}

		$tableHtml = $tableHtml .'</table>';

		$this->view->orders = $tableHtml;

	}


	public function indexAction() {
		$userMapper = new Front_Model_UserMapper();
		$uid  = $this->getRequest()->getParam('user');
		if (isset($uid)) {


		} else {
			// Find normal users
			$users = $userMapper->findUserByRole(2);
			if(isset($users)) {
				$defaultUser = $users[0];
				$uid = $defaultUser->_uid;
			}

		}
		$this->createMainPage($uid, 'create');

	}

	protected function createMainPage($uid, $type) {
		if (isset($uid)) {
			$userMapper = new Front_Model_UserMapper();
			$userInfo = new Front_Model_User();
			$has = $userMapper->find($uid, $userInfo);
			$users = $userMapper->findUserByRole(2);
			if (isset($has) && isset($users)) {
				$this->buildTableOrders($uid);
				$this->view->name = $userInfo->_fullname;
				$userForm = $this->buildUserForm($users, $userInfo);
				//
				$remainForm = $this->buildRemainForm($userInfo);
				//
				$orderForm = $this->buildOrderForm($type, $userInfo);

			}
		}
	}

	public function addorderAction() {
		//$this->buildTableSchedules();
		$uid  = $this->getRequest()->getParam('user');
		if (isset($uid)) {
			$this->createMainPage($uid, 'create');
			if ($this->getRequest()->isPost() ) {
				$formData = $this->getRequest()->getPost();
				if ($this->_orderform->isValid($formData)) {
					$order = new User_Model_Order();
					$this->populateOrder($this->getRequest(), $order);
					$order->_uid = $uid;
					$order->_status = 0;

					$userMapper = new Front_Model_UserMapper();
					if ($userMapper->vaidateRemain($uid, $order->_quantity)) {
						$orderMapper = new User_Model_OrderMapper();
						$oid = $orderMapper->save($order);
						if ($oid > 0) {
							$reason = '';
							$quantity = -1 * $order->_quantity;
							$this->updateRemain($uid, $quantity, $reason);
						}
						$url = new Zend_View_Helper_Url();
						$action = $url->url(array('module'=>'admin',
					'controller'=> 'order','action'=>'index','user' => $uid),
						NULL, TRUE);
						$this->getResponse()->setRedirect($action);
					} else {
						$this->view->error =
							"<script type='text/javascript'>
							    alert('Remain not enought');
							</script>";
					}
				}
			}
		}
	}

	protected function populateOrder(Zend_Controller_Request_Abstract $request, User_Model_Order $order) {
		if (!isset($order)) {
			$order = new User_Model_Order();
		}
		$params = $request->getParams();
		if (isset($params)){
			$order->_date = $request->getParam('date');
			$order->_sid = $request->getParam('sid');
			//$order->_uid = $request->getParam('uid');
			$order->_type = $request->getParam('type');
			$order->_quantity = $request->getParam('quantity');
		}
	}

	public function updateorderAction() {
		$uid  = $this->getRequest()->getParam('user');
		$oid  = $this->getRequest()->getParam('menu');
		if (isset($uid) && isset($oid)) {
			$this->createMainPage($uid, 'update');
			if ($this->getRequest()->isPost() ) {
				$formData = $this->getRequest()->getPost();
				if ($this->_orderform->isValid($formData)) {
					$order = new User_Model_Order();
					$orderMapper = new User_Model_OrderMapper();
					$orderMapper->find($oid, $order);
					$oldquantity = $order->_quantity;
					$this->populateOrder($this->getRequest(), $order);
					$userMapper = new Front_Model_UserMapper();
					$quan = $order->_quantity - $oldquantity;
					if ($userMapper->vaidateRemain($uid, $quan)) {
						$orderMapper = new User_Model_OrderMapper();
						$orderMapper->save($order);
						$reason = '';
						$this->updateRemain($uid, -1 * $quan, $reason);
						$url = new Zend_View_Helper_Url();
						$action = $url->url(array('module'=>'admin',
						'controller'=> 'order','action'=>'index','user' => $uid),
						NULL, TRUE);
						$this->getResponse()->setRedirect($action);
					} else {
						$this->view->error =
							"<script type='text/javascript'>
							    alert('Remain not enought');
							</script>";
					}
				}
			}
		}
	}

	public function deleteorderAction() {
		$uid = $this->getRequest()->getParam('user');
		$oid  = $this->getRequest()->getParam('menu');
		if (isset($oid)) {
			$orderMapper = new User_Model_OrderMapper();
			$orderInfo = new  User_Model_Order();
			if ($orderMapper->find($oid, $orderInfo)) {
				if ($orderInfo->_status != 3) {
					if ($orderMapper->delete($oid)) {
						$reason = '';
						echo $orderInfo->_quantity;
						$this->updateRemain($uid, $orderInfo->_quantity, $reason);
						$url = new Zend_View_Helper_Url();
						$newLink = $url->url(array('module'=>'admin',
							'controller'=> 'order','action'=>'index','user' => $uid),
						NULL, TRUE);
						$this->getResponse()->setRedirect($newLink);
					}
				}
			}

		}
	}

	public function updateremainAction() {
		$uid = $this->getRequest()->getParam('user');
		$remain = $this->getRequest()->getParam('remain');
		if (isset($uid) && isset($remain)) {
			$userMapper = new Front_Model_UserMapper();
			$userInfo = new Front_Model_User();
			$has = $userMapper->find($uid, $userInfo);
			if (isset($has)) {
				$userInfo->_remain = $remain;
				$userMapper->save($userInfo);
				$url = new Zend_View_Helper_Url();
				$newLink = $url->url(array('module'=>'admin',
					'controller'=> 'order','action'=>'index','user' => $uid),
				NULL, TRUE);
				$this->getResponse()->setRedirect($newLink);
			}
		}
	}

	public function updateRemain($uid, $quantity, &$reason) {
		if (isset($uid) && isset($quantity)) {
			$userMapper = new Front_Model_UserMapper();
			$userInfo = new Front_Model_User();
			$has = $userMapper->find($uid, $userInfo);
			if (isset($has)) {
				$newRemain = $userInfo->_remain;
				$newRemain = $newRemain + $quantity;
				if ($newRemain < 0) {
					$reason = 'User remain not enough';
					return false;
				}
				$userInfo->_remain = $newRemain;
				$userMapper->save($userInfo);
			}
		}
		return true;
	}
}